<template>
	<view>
		<su-sticky zIndex="3" >
      <view class="sort-tabs">
				<view
					v-for="tab in tabList"
					:key="tab.key"
					class="sort-tab"
					:class="{ active: state.activeTab === tab.key }"
					@click="onTabClick(tab.key)"
				>
					{{ tab.label }}
					<view class="arrows">
						<view
							class="arrow up"
							:style="{
								'border-bottom-color': state.activeTab === tab.key && state.sortOrder === 'asc' ? '#e23d3d' : '#b3b3b3'
							}"
							@click.stop="onArrowClick(tab.key, 'asc')"
						></view>
						<view
							class="arrow down"
							:style="{
								'border-top-color': state.activeTab === tab.key && state.sortOrder === 'desc' ? '#e23d3d' : '#b3b3b3'
							}"
							@click.stop="onArrowClick(tab.key, 'desc')"
						></view>
					</view>
				</view>
			</view>
    </su-sticky>

		<!-- <view class="tabs">
			
		</view> -->
		<view class="goods" id="s-goods">
			
			<view class="goods-item" v-for="(item,index) in state.goodsList" :key="index">
				<image class="goods-img" :src="sheep.$url.cdn(item.image)" @click="goodsClick(item)"></image>
				<view class="content-box">
					<view class="goods-tag" v-if="tagInferShop(item).length > 0">
						<image v-for="(tag,index) in tagInferShop(item)"  :key="index" :src="sheep.$url.cdn(tag.img)" :class="tag.class"></image>
					</view>
					<view class="goods-title-box">
						<view class="goods-title ss-line-2" @click="goodsClick(item)">
							{{item.title}}
						</view>
					</view>
					<view class="goods-desc " @click="goodsClick(item)">
						<view class=" ss-flex ss-row-between" style="width:100%">
							<view class="desc ss-flex-row ss-col-bottom ss-row-left">
								<view class="dollar">¥</view>
								<!-- <view class="price ss-line-1">{{item.price[0]}}</view> -->
								<view class="price">
									<view class="price-text-integer">{{String(item.price[0]).split('.')[0]}}</view>
									<view class="price-text-decimal">.{{String(item.price[0]).split('.')[1]}}</view>
								</view>
							</view>
							<view class="sales ss-line-1">已抢{{item.sales}}件</view>
						</view>
					</view>
					<view class="share-sales ss-flex-row ss-row-between ss-col-center">
						<view class="merchant ss-flex-row ss-row-left ss-col-center" @click="goodsClick(item)">
							<view class="img"><image :src="sheep.$url.cdn(item?.store?.thumb||'/static/store/shop-default-avatar.png')"></image></view>
							<view class="merchant-name ss-line-1">{{item?.store?.name||'鲸囍优选'}}</view>
						</view>
						<view class="share" @click="share(item)">
							<view class="text">分享得3%</view>
							<image class="share-img" :src="sheep.$url.cdn('/storage/default/20250521/97829ea2a12e4b87a932b8bca92c9cdd.png')"></image>
						</view>
					</view>
				</view>
			</view>
			
			<view style="width: 100%;"  v-if="state.goodsList.length === 0 && state.loadStatus == 'no-more'">
				<s-empty icon="/static/soldout-empty.png" text="暂无商品" />
			</view>
			<view class="ss-flex ss-row-center" style="width: 100%;" 
				v-if="state.goodsList.length != 0 || state.loadStatus == 'loading'" >
				<uni-load-more :status="state.loadStatus"  @tap="loadMore" />
			</view>
		</view>
	</view>
</template>

<script setup>
	import sheep from '@/sheep'
	import {tagInferShop} from "@/sheep/helper/tools.js"
	import {
		ref,
		reactive,
		onMounted,
		computed,
		getCurrentInstance
	} from 'vue';
	import {
		onShow,
		onHide,
		onReachBottom,
		onPageScroll,
		onUnload,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import _ from 'lodash';
	
	import mitt from '@/sheep/mitt.js';
	const statusBarHeight = sheep.$platform.device.statusBarHeight;
	const state = reactive({
		scrollTop:0,
		loadStatus:'more',
		isLoading: false,
		categoryId:'',
		pages: 0,
		goodsList: [],
		currentTab: 0,
		activeTab: '',
    sortOrder: 'desc' // 'asc' or 'desc'
	});
	const props = defineProps({
		data: {
			type: Object,
			default () {},
		},

	});

	const tabList = [
		{ key: '', label: '综合' },
		{ key: 'sales', label: '销量' },
		{ key: 'price', label: '价格' },
		{ key: 'create_time', label: '新品' }
	]

	const apiMode = computed(()=>props.data.goodsIds.length == 0)

	const onTabClick = (tabKey) => {
		if (state.activeTab === tabKey) {
			// 切换排序方向
			state.sortOrder = state.sortOrder === 'asc' ? 'desc' : 'asc';
		} else {
			state.activeTab = tabKey;
			state.sortOrder = 'desc'; // 默认降序
		}
		// 这里可以触发排序逻辑
		console.log(state.activeTab,state.sortOrder,'tttt')
		resetList()
	}
	const onArrowClick = (tabKey, order) => {
		if (state.activeTab === tabKey && state.sortOrder === order) return;
		state.activeTab = tabKey;
		state.sortOrder = order;
		// 这里可以触发排序逻辑
		console.log(state.activeTab,state.sortOrder,'oooooooo')
		resetList()
	}

	function goodsClick(item) {
		uni.navigateTo({
			url: '/pages/goods/index?id=' + item.id
		})
	}
	onPageScroll((e)=>{
		state.scrollTop = Number(e.scrollTop.toFixed(0))
	})
	onShow(()=>{
		uni.$on('categorylist',onCategorylist)
	})
	onHide(()=>{
		uni.$off('categorylist',onCategorylist)
	})
	onPullDownRefresh(()=>{
		uni.$off('categorylist',onCategorylist)
		setTimeout(()=>{
			uni.$on('categorylist',onCategorylist)
		},800)
	})
	function commission(goods){
		return Number((goods.price[0]*0.03).toFixed(2)).toString()
	}
	async function onCategorylist(id){
		state.categoryId = id == -999 ? '':id 
		if(apiMode.value){
			state.pages = 0,
			state.goodsList = []
			await getGoodsList()
			offsetPageTop()
		}
	}
	const { proxy }= getCurrentInstance()
	const Tmp = computed(() => props.data.goodsIds);

	onReachBottom(() => {
		loadMore()
	})
	function loadMore(){
		if (state.loadStatus == 'no-more') return uni.showToast({
			title: '没有更多了',
			icon: 'none'
		})
		if (!state.isLoading) {
			state.pages += 1
			getGoodsList()
		}
	}
	async function getGoodsList(){
		if(apiMode.value){
			await apiGetList()
		}else{
			idGetList()
		}
	}
	function resetList(){
		state.pages = 0
		state.goodsList = []
		getGoodsList()
	}
	async function apiGetList(){
		if (state.isLoading) return
		state.loadStatus = 'loading'
		const res = await sheep.$api.goods.list({
		  category_id: state.categoryId|| '',
		  page:state.pages,
		});
		if (res.error === 0) {
		  let couponList = _.concat(state.goodsList, res.data.data);
		  state.goodsList = couponList
		  if(res.data.per_page > res.data.data.length){
			  state.loadStatus = 'no-more'
		  }else{
			  state.loadStatus = 'more'
		  }
		}
		state.isLoading = false
	}

	// Fisher-Yates (Knuth) 洗牌算法
	function shuffleArray(array) {
			// 创建数组的副本，避免修改原数组
			const shuffled = [...array];
			
			// 从后向前遍历数组
			for (let i = shuffled.length - 1; i > 0; i--) {
					// 生成一个随机索引，范围是 [0, i]
					const j = Math.floor(Math.random() * (i + 1));
					// 交换当前元素和随机位置的元素
					[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
			}
			
			return shuffled;
	}
	async function idGetList() {
		if (state.isLoading) return
		state.loadStatus = 'loading'
		state.isLoading = true
		let ids = Tmp.value.slice(state.pages * 10, (state.pages + 1) * 10)
		if (ids.length == 0) {
			state.loadStatus = 'no-more'
			return
		}else{
			state.loadStatus = 'more'
		}
		let shuffleIds = ids
		// const shuffleIds = shuffleArray(ids)
		
		// 洗牌顺序
		if (state.activeTab == '') {
			shuffleIds = shuffleArray(ids)
		}

		let list = await getGoodsListByIds(shuffleIds.join(','));
		state.isLoading = false
		state.goodsList.push(...list)

	}
	function rpxtopx(rpx){
		// #ifdef APP
		return uni.upx2px(rpx)
		// #endif
		// #ifndef APP
		return uni.rpx2px(rpx)
		// #endif
	}
	function offsetPageTop(){
		if(apiMode.value){
			// #ifdef MP
			let offsetTop = 80 + Number(statusBarHeight)
			// #endif
			// #ifdef H5
			let offsetTop = Number(uni.rpx2px(140)) + Number(statusBarHeight)
			// #endif
			// #ifdef APP
			let offsetTop = Number(uni.upx2px(140)) + Number(statusBarHeight)
			// #endif
			uni.createSelectorQuery().in(proxy).select("#s-goods")
			  .boundingClientRect((data) => {
				 if(data?.top && data.top !== offsetTop ){
				 	uni.pageScrollTo({
				 		duration:240,
				 		scrollTop:state.scrollTop + ( data.top - offsetTop)
				 	})
				 }
			  })
			  .exec();
		}
	}
	async function getGoodsListByIds(ids) {
		let {
			data
		} = await sheep.$api.goods.ids1({
			ids,
			sort: state.activeTab,
			order: state.sortOrder,
			is_list: 1
		});
		return data;
	}

	onMounted(() => {
		getGoodsList()
	})
	
	function share(item){
		mitt.emit('indexGoodShare',{good:item})
	}
	
</script>

<style lang="scss" scoped>
	.goods {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: flex-start;
		width: 100%;
		box-sizing: border-box;
		.goods-item {
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			justify-content: flex-start;
			width: calc((100% - 25rpx) / 2);
			margin-top: 25rpx;
			border-radius: 20rpx;
			background: #fff;
			.goods-img {
				max-width: 100%;
				height: 350rpx;
				border-radius: 12rpx 12rpx 0 0;
			}

			.goods-title-box {
				min-height: 70rpx;
			}
			.goods-title {
				margin-top: 13rpx;
				width: calc(100% - 20rpx);
				color: #484848;
				font-size: 28rpx;
				font-weight: bold;
				font-family: PingFang-SC-Bold;
			}

			.goods-desc {
				width:100%;
				display: flex;
				flex-direction: column;
				// justify-content: space-between;
				align-items: center;
				margin-top: 10rpx;
				margin-bottom: 4rpx;
				box-sizing: border-box;
			
				.desc {
					font-family: Source Han Sans;
					color: #FB0036;
					font-family: Source Han Sans;
					font-weight: 700;
					display: flex;
					align-items: baseline;

					.price {
						display: flex;
						align-items: baseline;
						.price-text-integer {
							font-size: 46rpx;
						}
						.price-text-decimal {
							font-size: 32rpx;
						}
					}

					.dollar {
						font-size: 26rpx;
						display: flex;
					}
				}
				
				.sales {
					font-family: PingFang-SC-Regular;
					font-size: 22rpx;
				
					color: #969696;
				}
			}
			.share-sales {
				
				.merchant{
					.img {
						width: 42rpx;
						height: 32rpx;
						min-width: 42rpx;
						min-height: 32rpx;
						margin-right: 4rpx;
						image {
							width: 100%;
							height: 100%;
						}
					}
					.merchant-name{
						font-family: Source Han Sans;
						font-size: 24rpx;
						color: #969696;
						
						overflow: hidden;
						// white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
				
				.shareBox{
					display: flex;
					align-items: center;
					border-radius: 8rpx;
					background-color: rgba( 41,109,221,0.15);
					.shareBox-icon{
						height:34rpx;
						width:34rpx;
						min-width: 34rpx;
						margin-right: 8rpx;
						border-radius: 8rpx 0 16rpx 0;
						background-color: #296DDD;
						display:flex;
						align-items: center;
						justify-content: center;
						.iconBox{
							display:flex;
							align-items: center;
							justify-content: center;
							height:24rpx;
							width:24rpx;
							border-radius: 50%;
							background-color: #fff;
						}
					}
					.shareBox-text{
						padding-right: 6rpx;
						font-size: 20rpx;
						color: #296DDD;
						vertical-align: middle;
						line-height: 1;
					}
				}
				.share {
					display: flex;
					align-items: center;
					.text {
						color: #FB0036;
						font-size: 24rpx;
						margin-right: 2rpx;
						min-width: 110rpx;
						text-align: right;
					}
					.share-img {
						width: 40rpx;
						height: 40rpx;
					}
				}
			}
		}

		.goods-item:nth-child(2n-1) {
			margin-right: 25rpx;
		}
		.goods-item:nth-of-type(1), .goods-item:nth-of-type(2) {
			margin-top: 0;
		}

	}

	.blank {
		background-color: #fff;
		height: 44rpx;
		width: 100%;
	}
	.goods-tag {
		display: flex;
		align-items: center;
		image {
			margin-right: 10rpx;
		}
		image:last-child {
			margin-right: 0;
		}
		.hot {
			width: 60rpx;
			height: 24rpx;
		}
		.new {
			width: 60rpx;
			height: 24rpx;
		}
		.good {
			width: 100rpx;
			height: 24rpx;
		}
		.day7 {
			width: 114rpx;
			height: 24rpx;
		}
	}
	.content-box {
		padding: 22rpx 18rpx 22rpx;
	}
	.tabs {
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: sticky;
		top: 0;
		z-index: 199;
		padding: 0 80rpx;

		.tab {
			color: #787878;
			font-size: 28rpx;
		}

		.active {
			color: #202020;
			font-weight: bold;
		}
}


.sort-tabs {
  display: flex;
  padding: 10px 0;
	background-color: #f7f7f7;
}
.sort-tab {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #787878;
  position: relative;
  cursor: pointer;
  user-select: none;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
}
.sort-tab.active {
  color: #202020;
  font-weight: bold;
}
.arrows {
  display: inline-flex;
  flex-direction: column;
  margin-left: 2px;
  height: 18px;
  justify-content: center;
}
.arrow {
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  margin: 0 auto;
  margin-bottom: 1px;
}
.arrow.up {
  border-bottom: 6px solid #b3b3b3;
  border-top: none;
}
.arrow.down {
  border-top: 6px solid #b3b3b3;
  border-bottom: none;
  margin-bottom: 0;
}
.sort-tab.active .arrow.up {
  border-bottom-color: v-bind('state.sortOrder === "asc" ? "#FB0036" : "#ccc"');
}
.sort-tab.active .arrow.down {
  border-top-color: v-bind('state.sortOrder === "desc" ? "#FB0036" : "#ccc"');
}

</style>